package com.kfm.util;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

public class CaptchaUtil {

    //放到Session空间中的key
    public static final String RANDOMCODEKEY = "RANDOMVALIDATECODEKEY";
    private Random random = new Random();
    //验证码中字符的来源
    private String randString = "0123456789ABCDEFGHIGKLMNOPQRLTUVWXYZ";  	private int width = 80; // 验证码图片的宽
    private int height = 26; // 验证码图片的高
    private int lineSize = 80;  //验证码干扰线数量，干扰线是防止验证码被破解的
    private int stringNum = 4;  //验证码中字符的数量
    /**
     * 获得字体
     */
    private Font getFont() {
        return new Font("Times New Roman", Font.ROMAN_BASELINE, 18);
    }
    /**
     * 获得颜色
     */
    private Color getRandColor() {
        int r = random.nextInt(256);
        int g = random.nextInt(256);
        int b = random.nextInt(256);
        return new Color(r, g, b);
    }
    /**
     * 生成随机数图片
     */
    public void getRandcode(HttpServletRequest request,
                            HttpServletResponse response) throws Exception {
        // 创建HttpSession对象
        HttpSession session = request.getSession();
        //在内存中创建一副指定宽度，高度，背景色的图像，验证码将绘制在这幅图像上
        BufferedImage image = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);
        //产生image对象的Graphics对象，该对象可在图像上进行各种绘制操作，相当于画笔
        Graphics g = image.getGraphics();
        //设定画笔的边框
        g.fillRect(0, 0, width, height);
        //设定画笔的颜色
        g.setColor(getRandColor());
        //画笔已设置完毕，开始绘制验证码的干扰线
        for (int i = 0; i <= lineSize; i++) {
            drawLine(g);
        }
        //开始绘制验证码，并将验证码保存到randomString变量中
        String randomString = "";
        for (int i = 0; i <= stringNum; i++) {
            randomString = drawString(g, randomString, i);
        }
        //将完整的验证码字符串保存到session中，用于下次验证
        session.removeAttribute(RANDOMCODEKEY);
        session.setAttribute(RANDOMCODEKEY, randomString);
        //销毁画笔
        g.dispose();
        //将验证码图片响应到输出流中，发送给浏览器
        ImageIO.write(image, "JPEG", response.getOutputStream());
    }
    /**
     * 绘制验证码到图片上
     */
    private String drawString(Graphics g, String randomString, int i) {
        //设置画笔字体
        g.setFont(getFont());
        //设置画笔颜色
        g.setColor(new Color(random.nextInt(101), random.nextInt(111),
                random.nextInt(121)));
        //设置画笔在x方向和y方向随机变换3个像素
        g.translate(random.nextInt(3), random.nextInt(3));
//生成验证码中的一个字符
        String rand = String.valueOf(getRandomString(random
                .nextInt(randString.length())));
        //将验证码字符连接到验证码字符串中
        randomString += rand;
        //将验证码字符rand绘制到图片上，x坐标是每个字符的宽度13*个数i,y坐标是16
        g.drawString(rand, 13 * i, 16);
        //将完整的验证码字符串返回
        return randomString;
    }
    /**
     * 绘制干扰线
     */
    private void drawLine(Graphics g) {
        int x = random.nextInt(width);
        int y = random.nextInt(height);
        int xl = random.nextInt(13);
        int yl = random.nextInt(15);
        g.drawLine(x, y, x + xl, y + yl);//参数分别为起点x,y坐标，终点x,y坐标
    }
    /**
     * 获得随机的字符
     */
    public String getRandomString(int num) {
        return String.valueOf(randString.charAt(num));
    }
}
